#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import QFileDialog, QTextCursor, QTextEdit, QColor, QComboBox, QTableWidgetItem
from PyQt4.Qt import Qt
import re
from widget.tools import MessageBox

__author__ = 'xiwei'


class ROW:
    def __init__(self):
        pass

    RULE = 0
    PREVIEW = 1
    NAME = 2
    TYPE = 3


class LogHandler:
    def __init__(self, ui):
        """
            init func
        Args:
            ui (UI.App): ui

        """
        self.ui = ui

        self.file_edit = self.ui.lineEdit_log_file
        self.rule_edit = self.ui.lineEdit_log_re
        self.error_label = self.ui.label_log_re_error

        self.field_table = self.ui.tableWidget_log_field

        self.btn_add_rule = self.ui.pushButton_log_re
        self.btn_add_rule.setDisabled(True)

        self.text_view = self.ui.plainTextEdit_log_txt
        self.data = []

        self.error = None

        self.select_color = QColor(Qt.gray)

        self.init_field_table()

    def init_field_table(self):
        self.field_table.setRowCount(4)
        self.field_table.setVerticalHeaderLabels([u'规则', u'预览', u'字段名', u'字段类型'])

    def file_select(self):
        # log_file = QFileDialog().getOpenFileName()
        log_file = '/Users/haizhi/bdp/logs/opends_service.log'
        self.file_edit.clear()
        self.file_edit.setText(log_file)

        with open(log_file, 'r') as log:
            for line in xrange(0, 5):
                data = log.readline()
                self.data.append(data)
            self.text_view.setPlainText(''.join(self.data))
            log.seek(0)
            self.common_detect(log.readline())

    def common_detect(self, line):
        pass

    def rule_change(self, rule):
        """
            handler the change for rule text edit
        Args:
            rule (str): current rule

        Returns:

        """
        offset = 0
        selections = []
        if rule == '':
            self.btn_add_rule.setDisabled(True)
            return
        for line in self.data:
            try:
                words = re.finditer(str(rule), line)
                self.text_view.moveCursor(QTextCursor.Start)
                for word in words:
                    start, end = word.span()
                    selection = QTextEdit.ExtraSelection()
                    selection.format.setBackground(self.select_color)
                    selection.cursor = self.text_view.textCursor()
                    selection.cursor.setPosition(start + offset)
                    selection.cursor.setPosition(end + offset, QTextCursor.KeepAnchor)
                    selections.append(selection)
                self.error = None
                self.error_label.clear()
                self.btn_add_rule.setDisabled(False)
            except Exception, e:
                self.error = str(e)
                self.error_label.setText(u'错误:%s' % self.error)
                self.btn_add_rule.setDisabled(True)
            offset += len(str(line))
        self.text_view.setExtraSelections(selections)

    def rules(self):
        """
            get the current rules in field table
            Returns:
                rules (list): the current rules in field table.
        """
        max_col = self.field_table.columnCount()
        return [str(self.field_table.item(ROW.RULE, col).text()) for col in xrange(0, max_col)]

    def add_rule(self):
        rule = str(self.rule_edit.text())
        if self.error:
            MessageBox().information(self.ui, u'提示', u'当前规则存在错误.', MessageBox.Ok)
            return
        if rule in self.rules():
            ret = MessageBox().information(self.ui, u'提示', u'已存在相同的规则,是否继续?', MessageBox.Ok | MessageBox.No)
            if ret == MessageBox.No:
                return
        self.add_field((rule, 'preview', 'name'))

    def add_field(self, field):
        """
            add a field into table_widget
        Args:
            field (tuple): (rule, preview, name) the field tuple
        """
        data_type = ['string', 'number', 'date']
        combo = QComboBox()
        combo.addItems(data_type)
        column = self.field_table.columnCount()

        self.field_table.setColumnCount(column + 1)

        self.field_table.setItem(ROW.RULE, column, QTableWidgetItem(field[ROW.RULE]))
        self.field_table.setItem(ROW.PREVIEW, column, QTableWidgetItem(field[ROW.PREVIEW]))
        self.field_table.setItem(ROW.NAME, column, QTableWidgetItem(field[ROW.NAME]))
        self.field_table.setCellWidget(ROW.TYPE, column, combo)

    def delete_field(self, index):
        pass

    def table_cell_changed(self, row, col):
        print row, col
